package bp.wf.httphandler;

import bp.ccbill.template.DBRole;
import bp.ccbill.template.DBRoleAttr;
import bp.ccbill.template.DBRoles;
import bp.da.*;
import bp.difference.handler.CommonFileUtils;
import bp.sys.SysEnum;
import bp.sys.SysEnums;
import bp.tools.AesEncodeUtil;
import bp.tools.FileAccess;
import bp.tools.StringUtils;
import bp.web.*;
import bp.en.*;
import bp.wf.template.*;
import bp.difference.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;

/**
 页面功能实体
*/
public class WF_CommTS extends bp.difference.handler.DirectoryPageBase
{

		///#region 参数
	public final String getParas()
	{
		return this.GetRequestVal("Paras");
	}
	public final String getOrderBy()
	{
		return this.GetRequestVal("OrderBy");
	}

	public final String getClassID()
	{
		return this.GetRequestVal("ClassID");
	}
	/**
	 关联服务器端的实体类.
	*/
	public final String getRefEnName()
	{
		String str = this.GetRequestVal("RefEnName");
		if (!DataType.IsNullOrEmpty(str))
		{
			str = str.replace("TS.", "BP.");
		}
		return str;
	}
	public final String getKVs()
	{
		return this.GetRequestVal("KVs");
	}
	public final String getMap()
	{
		return this.GetRequestVal("Map");
	}
	public final String getPK()
	{
		return this.GetRequestVal("PK");
	}
	public final String getPKVal()
	{
		return this.GetRequestVal("PKVal");
	}
	public final int getPKValInt()
	{
		String str = this.GetRequestVal("PKVal");


		if (DataType.IsNullOrEmpty(str) == true)
		{
			str = this.GetRequestVal("WorkID");
		}
		else
		{
			return Integer.parseInt(str);
		}

		if (DataType.IsNullOrEmpty(str) == true)
		{
			str = this.GetRequestVal("NodeID");
		}
		else
		{
			return Integer.parseInt(str);
		}

		if (DataType.IsNullOrEmpty(str) == true)
		{
			str = this.GetRequestVal("OID");
		}
		else
		{
			return Integer.parseInt(str);
		}

		if (DataType.IsNullOrEmpty(str) == true)
		{
			str = "0";
		}

		return Integer.parseInt(str);
	}

		///#endregion 参数

	/**
	 构造函数
	*/
	public WF_CommTS()
	{
		//string sql="xxxx";
		//DBAccess.RunSQLReturnTable(sql);
	}


		///#region 页面类.
	/**
	 从表移动

	 @return
	*/
	public final String DtlSearch_UpdatIdx() throws Exception {
		Map map = bp.ents.Glo.GenerMap(this.getClassID());

		String pk = "No";
		if (map.getAttrs().contains("No") == true)
		{
			pk = "No";
		}
		else if (map.getAttrs().contains("OID") == true)
		{
			pk = "OID";
		}
		else if (map.getAttrs().contains("MyPK") == true)
		{
			pk = "MyPK";
		}
		else if (map.getAttrs().contains("NodeID") == true)
		{
			pk = "NodeID";
		}
		else if (map.getAttrs().contains("WorkID") == true)
		{
			pk = "WorkID";
		}

		String[] pks = this.GetRequestVal("PKs").split("[,]", -1);
		int idx = 0;
		for (String str : pks)
		{
			if (DataType.IsNullOrEmpty(str) == true)
			{
				continue;
			}
			idx++;
			String sql = "UPDATE " + map.getPhysicsTable() + " SET Idx=" + idx + " WHERE " + pk + "='" + str + "'";
			DBAccess.RunSQL(sql);
		}


			///#region 特殊业务处理.
		if (this.getClassID().equals("TS.WF.Cond") == true)
		{
			//判断设置的顺序是否合理？
			Cond cond = new Cond();
			String pkval = pks[0];
			cond.setMyPK(pkval);
			cond.Retrieve();

			return WF_Admin_Cond2020.List_DoCheckExt(cond.getCondTypeInt(), cond.getNodeID(), cond.getToNodeID());
		}

			///#endregion 特殊业务处理.


		return "移动成功.";
	}

	/**
	 更新排序

	 @return
	*/
	public final String TreeEns_UpdateDtlIdx() {
		String idList = this.GetRequestVal("PKs");
		if (StringUtils.isBlank(idList)) {
			return "err@请传入排序集合";
		}
		String tableName = this.GetRequestVal("PTable");
		if (StringUtils.isBlank(tableName)) {
			return "err@请传入物理表名";
		}
		String tablePK = this.GetRequestVal("PK");
		if (StringUtils.isBlank(tablePK)) {
			return "err@请传入物理表主键";
		}

		String[] targetIdList = Arrays.stream(idList.split(",", -1)).filter(StringUtils::isNotBlank).toArray(String[]::new);
		targetIdList = Arrays.stream(targetIdList).map(s -> "'" + s + "'").toArray(String[]::new);
		String minIdxSQL = "SELECT MIN(Idx) FROM " + tableName + " WHERE " + tablePK + " in (" + String.join(",", targetIdList) + ")";
		int minIdx = DBAccess.RunSQLReturnValInt(minIdxSQL);

		// 更新其他部分sql
		String updateOthersSQL = "Update " + tableName + " SET Idx = Idx + " + targetIdList.length + " WHERE Idx = 0";
		DBAccess.RunSQL(updateOthersSQL);
		StringBuilder batchUpdateIdxSQL = new StringBuilder();
		for(String id : targetIdList) {
			batchUpdateIdxSQL.append("Update ")
					.append(tableName)
					.append(" SET Idx=")
					.append(minIdx)
					.append(" WHERE ")
					.append(tablePK)
					.append("=")
					.append(id)
					.append(";");
			minIdx++;
		}
		DBAccess.RunSQLs(batchUpdateIdxSQL.toString());
		return "排序成功";
//
//
//		String ptable = this.GetRequestVal("PTable");
//		String pk = this.GetRequestVal("PK");
//		int idx = 0;
//		int minIdx = DBAccess.RunSQLReturnValInt("SELECT min(Idx) FROM " + ptable + " WHERE " + pk + "in (" + pk + ")");
//		for (String str : pks)
//		{
//			if (DataType.IsNullOrEmpty(str))
//			{
//				continue;
//			}
//			idx++;
//			String sql = "UPDATE " + ptable + " SET Idx='" + idx + "' WHERE " + pk + "='" + str + "'";
//			DBAccess.RunSQL(sql);
//		}
//		return "执行成功.";
	}

		///#endregion 页面类.

	/**
	 加入map到缓存.
	 @return
	*/
	public final String Entity_SetMap() throws Exception {
		String key = SystemConfig.getIsEncryptionKey();
		String mapInfo = this.getMap();
		String uriComponent = AesEncodeUtil.decryptAES(mapInfo, key);
		String finalDecodedString = URLDecoder.decode(uriComponent, StandardCharsets.UTF_8.name());
		Map myMap = bp.ents.Glo.SetMap(this.getClassID(), finalDecodedString);

        String versionCode = this.GetRequestVal("VersionCode");
        if (DataType.IsNullOrEmpty(versionCode))
        {
		    Cache.SetMapTS(this.getClassID(), myMap);
            return "1";
        }

        try
        {
            long version = Long.parseLong(versionCode);
            boolean updated = Cache.SetMapTS(this.getClassID(), myMap, version);
            if (updated)
                return "1";
            else
                return "2";
        }
        catch (NumberFormatException ex)
        {
            return "err@非法参数";
        }
	}
	/**
	 检查是否存在Map
	 @return
	*/
	public final String Entity_IsExitMap()
	{
		//缓存map.
		if (bp.ents.Glo.IsExitMap(this.getClassID()))
		{
			return "1";
		}

		return "0";
	}
	public final String Entity_IsExits() throws Exception {
		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID());
			en.setNo(this.getPKVal());
			if (en.getIsExits() == true)
			{
				return "1";
			}
			return "0";
		}

		if (this.getPK().equals("MyPK"))
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID());
			en.setMyPK(this.getPKVal());
			if (en.getIsExits() == true)
			{
				return "1";
			}
			return "0";
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID());
			en.setOID(Integer.parseInt(this.getPKVal()));
			if (en.getIsExits()==true)
			{
				return "1";
			}
			return "0";
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID());
			en.setWorkID(Integer.parseInt(this.getPKVal()));
			if (en.getIsExits()==true)
			{
				return "1";
			}
			return "0";
		}
		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID());
			en.setNodeID(Integer.parseInt(this.getPKVal()));
			if (en.getIsExits()== true)
			{
				return "1";
			}
			return "0";
		}

		throw new RuntimeException("err@没有判断的entity类型.");
	}

	/**
	 执行insert方法.

	 @return
	*/
	public final String Entity_Insert() throws Exception {
		JSONObject json = JSONObject.parseObject(this.GetRequestVal("Row"));
		bp.sys.base.Glo.WriteEntityLog("实体数据写入");
		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.Insert();
			return en.ToJson(true);
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			if(en.GetValIntByKey("Idx", -1) == -1){
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMddHHmmss");
				en.SetValByKey("Idx", Integer.parseInt(dtf.format(LocalDateTime.now())));
			}
			en.Insert();
			return en.ToJson(true);
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			if(en.getOID()!=0)
				en.InsertAsOID(en.getOID());
			else
				en.Insert();
			return en.ToJson(true);
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.Insert();
			return en.ToJson(true);
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.Insert();
			return en.ToJson(true);
		}

		throw new RuntimeException("err@没有判断的entity类型.");
	}
	/**
	 根据

	 @return
	*/
	public final String Entity_GenerSQLAttrDB() throws Exception {
		String attrKey = this.GetRequestVal("AttrKey"); //  "SELECT * FROM WHERE XX=@SortNo ";
		JSONObject json = JSONObject.parseObject(this.GetRequestVal("Row"));
		DataTable dt = null;
		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				en.SetValByKey(key.toString(),value);
			}

			Attr attr = en.getEnMap().GetAttrByKey(attrKey);
			String sql = attr.getUIBindKey();
			sql = bp.wf.Glo.DealExp(sql, en);
			dt = DBAccess.RunSQLReturnTable(sql);
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				en.SetValByKey(key.toString(),value);
			}

			Attr attr = en.getEnMap().GetAttrByKey(attrKey);
			String sql = attr.getUIBindKey();
			sql = bp.wf.Glo.DealExp(sql, en);
			dt = DBAccess.RunSQLReturnTable(sql);
		}
		if (this.getPK().equals("WorkID") == true ||this.getPK().equals("OID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				en.SetValByKey(key.toString(),value);
			}
			Attr attr = en.getEnMap().GetAttrByKey(attrKey);
			String sql = attr.getUIBindKey();
			sql = bp.wf.Glo.DealExp(sql, en);
			dt = DBAccess.RunSQLReturnTable(sql);
		}

		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				en.SetValByKey(key.toString(),value);
			}

			Attr attr = en.getEnMap().GetAttrByKey(attrKey);
			String sql = attr.getUIBindKey();
			sql = bp.wf.Glo.DealExp(sql, en);
			dt = DBAccess.RunSQLReturnTable(sql);
		}
		if(dt == null)
			return "";
		if (SystemConfig.getAppCenterDBFieldCaseModel() != FieldCaseModel.None)
		{
			String columnName = "";
			for(DataColumn col : dt.Columns)
			{
				columnName = col.ColumnName.toUpperCase();
				switch (columnName)
				{
					case "NO":
						col.ColumnName = "No";
						break;
					case "NAME":
						col.ColumnName = "Name";
						break;
				}
			}
		}
		return bp.tools.Json.ToJson(dt);

	}
	public final String Entity_Save() throws Exception {
		JSONObject json = JSONObject.parseObject(this.GetRequestVal("Row"));
		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true)
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			int i = en.Save();

			return String.valueOf(i);
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true)
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			int i = en.Save();
			return String.valueOf(i);
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true)
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			int i = en.Save();
			return String.valueOf(i);
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true)
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			int i = en.Save();
			return String.valueOf(i);
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true)
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			int i = en.Save();
			return String.valueOf(i);
		}

		throw new RuntimeException("err@没有判断的entity类型.");

	}
	public final boolean checkPower(String classID, String pkval)
	{
		if (classID.contains("BP.WF.Template") == true && WebUser.getIsAdmin() == false)
		{
			throw new RuntimeException("非法用户.");
		}

		return true;
	}
	/**
	 执行更新

	 @return
	*/
	public String Entity_Update() throws Exception {
		JSONObject json = JSONObject.parseObject(this.GetRequestVal("Row"));
		bp.sys.base.Glo.WriteEntityLog("实体数据更新");
		if (this.getPK().equals("No")) {
			TSEntityNoName en = new TSEntityNoName(this.getClassID(), this.getPKVal());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value) || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.setNo(this.getPKVal());
			int i = en.Update();
			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (!DataType.IsNullOrEmpty(this.getRefEnName()))
			{
				String paraFields = en.getEnMap().ParaFields;
				if(DataType.IsNullOrEmpty(paraFields)) paraFields="";
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				for (Object key : json.keySet()) {
					if(key == null)
						continue;
					String value = json.getString(key.toString());
					if(DataType.IsNullOrEmpty(value) || value.equals("null"))
						value = "";
					enServ.SetValByKey(key.toString(),value);
					if(paraFields.contains(","+key.toString()+","))
						enServ.SetPara(key.toString(),value);
				}

				enServ.Update();
			}
			//AtPara字段存储异常的问题

			return String.valueOf(i);
		}

		if (this.getPK().equals("MyPK"))
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID(), this.getPKVal());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value) || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.setMyPK(this.getPKVal());
			int i = en.Update();
			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (!DataType.IsNullOrEmpty(this.getRefEnName()))
			{
				String paraFields = en.getEnMap().ParaFields;
				if(DataType.IsNullOrEmpty(paraFields)) paraFields="";
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				for (Object key : json.keySet()) {
					if(key == null)
						continue;
					String value = json.getString(key.toString());
					if(DataType.IsNullOrEmpty(value) || value.equals("null"))
						value = "";
					enServ.SetValByKey(key.toString(),value);
					if(paraFields.contains(","+key.toString()+","))
						enServ.SetPara(key.toString(),value);
				}
				enServ.Update();

				//把变更后的值给,TS实体.
				Row row = enServ.getRow();
				for (String key : row.keySet())
				{
					en.getRow().SetValByKey(key, row.get(key));
				}
			}
			return String.valueOf(i);
		}

		if (this.getPK().equals("OID"))
		{
			TSEntityOID en = new TSEntityOID(this.getClassID(), this.getPKValInt());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value) || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.setOID(this.getPKValInt());
			int i =en.Update();
			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (!DataType.IsNullOrEmpty(this.getRefEnName()))
			{
				String paraFields = en.getEnMap().ParaFields;
				if(DataType.IsNullOrEmpty(paraFields)) paraFields="";
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKValInt());
				enServ.RetrieveFromDBSources();
				for (Object key : json.keySet()) {
					if(key == null)
						continue;
					String value = json.getString(key.toString());
					if(DataType.IsNullOrEmpty(value) || value.equals("null"))
						value = "";
					enServ.SetValByKey(key.toString(),value);
					if(paraFields.contains(","+key.toString()+","))
						enServ.SetPara(key.toString(),value);
				}
				enServ.Update();
			}


			return String.valueOf(i);
		}

		if (this.getPK().equals("NodeID"))
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID(), this.getPKValInt());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value) || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.setNodeID(this.getPKValInt());
			int i = en.Update();
			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (!DataType.IsNullOrEmpty(this.getRefEnName()))
			{
				String paraFields = en.getEnMap().ParaFields;
				if(DataType.IsNullOrEmpty(paraFields)) paraFields="";
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				for (Object key : json.keySet()) {
					if(key == null)
						continue;
					String value = json.getString(key.toString());
					if(DataType.IsNullOrEmpty(value) || value.equals("null"))
						value = "";
					enServ.SetValByKey(key.toString(),value);
					if(paraFields.contains(","+key.toString()+","))
						enServ.SetPara(key.toString(),value);
				}
				enServ.Update();
			}


			return String.valueOf(i);
		}

		if (this.getPK().equals("WorkID"))
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID(), this.getPKValInt());
			for (Object key : json.keySet()) {
				if(key == null)
					continue;
				String value = json.getString(key.toString());
				if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
					value = "";
				en.SetValByKey(key.toString(),value);
			}
			en.setWorkID(this.getPKValInt());
			int i=en.Update();
			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (DataType.IsNullOrEmpty(this.getRefEnName()) == false)
			{
				String paraFields = en.getEnMap().ParaFields;
				if(DataType.IsNullOrEmpty(paraFields)) paraFields="";
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKValInt());
				enServ.RetrieveFromDBSources();
				for (Object key : json.keySet()) {
					if(key == null)
						continue;
					String value = json.getString(key.toString());
					if(DataType.IsNullOrEmpty(value)==true || value.equals("null"))
						value = "";
					enServ.SetValByKey(key.toString(),value);
					if(paraFields.contains(","+key.toString()+","))
						enServ.SetPara(key.toString(),value);
				}
				enServ.Update();
			}

			return String.valueOf(i);
		}

		throw new RuntimeException("err@没有判断的entity类型. Entity_Update ");
	}
	/**
	 查询
	 @return
	*/
	public final String Entity_Retrieve() throws Exception {

		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID(), this.getPKVal());
			return en.ToJson(true);
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID(), this.getPKVal());
			return en.ToJson(true);
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID(), getPKValInt());
			return en.ToJson(true);
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID(), this.getPKValInt());
			return en.ToJson(true);
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID(), this.getPKValInt());
			return en.ToJson(true);
		}

		throw new RuntimeException("err@没有判断的entity类型. Entity_Retrieve ");
	}
	/**
	 从数据库里查询.

	 @return
	*/
	public final String Entity_RetrieveFromDBSources() throws Exception {
		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID());
			en.setNo(this.getPKVal());
			int val = en.RetrieveFromDBSources();
			if (val == 0)
			{
				return "0";
			}
			return en.ToJson(true);
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID());
			en.setMyPK(this.getPKVal());
			int val = en.RetrieveFromDBSources();
			if (val == 0)
			{
				return "0";
			}
			return en.ToJson(true);
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID());
			en.setOID(this.getPKValInt());
			int val = en.RetrieveFromDBSources();
			if (val == 0)
			{
				return "0";
			}
			return en.ToJson(true);
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID());
			en.setWorkID(this.getPKValInt());
			int val = en.RetrieveFromDBSources();
			if (val == 0)
			{
				return "0";
			}
			return en.ToJson(true);
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID());
			en.setNodeID(this.getPKValInt());
			int val = en.RetrieveFromDBSources();
			if (val == 0)
			{
				return "0";
			}
			return en.ToJson(true);
		}

		throw new RuntimeException("err@没有判断的entity类型. Entity_Retrieve ");
	}
	public final String Entities_RetrieveAllFromDBSource() throws Exception {
		if (this.getPK().equals("No") == true)
		{
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			ens.RetrieveAllFromDBSource();
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			ens.RetrieveAllFromDBSource();
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			ens.RetrieveAllFromDBSource();
			return ens.ToJson("dt");
		}
		if (this.getPK().equals("WorkID") == true)
		{
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			ens.RetrieveAllFromDBSource();
			return ens.ToJson("dt");
		}
		if (this.getPK().equals("NodeID") == true)
		{
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			ens.RetrieveAllFromDBSource();
			return ens.ToJson("dt");
		}
		throw new RuntimeException("err@没有判断的entity类型. Entities_RetrieveAllFromDBSource ");
	}
	public final String Entities_RetrieveAll() throws Exception {
		if (this.getPK().equals("No") == true)
		{
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			ens.RetrieveAll(this.getOrderBy());
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			ens.RetrieveAll(this.getOrderBy());
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			ens.RetrieveAll(this.getOrderBy());
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			ens.RetrieveAll(this.getOrderBy());
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			ens.RetrieveAll(this.getOrderBy());
			return ens.ToJson("dt");
		}

		throw new RuntimeException("err@没有判断的entity类型. Entities_RetrieveAll ");
	}
	public final String Entities_Retrieve() throws Exception {
		if (this.getPK().equals("No"))
		{
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			bp.wf.httphandler.WF_Comm hand = new WF_Comm();
			return hand.Entities_Init_Ext(ens, ens.getNewEntity(), this.getParas());
		}

		if (this.getPK().equals("MyPK"))
		{
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			bp.wf.httphandler.WF_Comm hand = new WF_Comm();
			return hand.Entities_Init_Ext(ens, ens.getNewEntity(), this.getParas());
		}

		if (this.getPK().equals("NodeID"))
		{
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			bp.wf.httphandler.WF_Comm hand = new WF_Comm();
			return hand.Entities_Init_Ext(ens, ens.getNewEntity(), this.getParas());
		}


		if (this.getPK().equals("WorkID"))
		{
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			bp.wf.httphandler.WF_Comm hand = new WF_Comm();
			return hand.Entities_Init_Ext(ens, ens.getNewEntity(), this.getParas());
		}

		if (this.getPK().equals("OID"))
		{
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			bp.wf.httphandler.WF_Comm hand = new WF_Comm();
			return hand.Entities_Init_Ext(ens, ens.getNewEntity(), this.getParas());
		}


		throw new RuntimeException("err@没有判断的 entity 类型. Entities_Retrieve ");
	}

	public final String Entities_RetrieveOR() throws Exception {
		String retrieveKey = this.GetRequestVal("Key");
		String retrieveVal = this.GetRequestVal("Val");
		String key1 = this.GetRequestVal("Key1");
		String val1 = this.GetRequestVal("Val1");
		String orderBy = this.GetRequestVal("OrderBy");
		if (this.getPK().equals("No") == true)
		{
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			QueryObject qo = new QueryObject(ens);
			qo.AddWhere(retrieveKey, retrieveVal);
			qo.addOr();
			qo.AddWhere(key1, val1);
			qo.addOrderBy(orderBy);
			qo.DoQuery();
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			QueryObject qo = new QueryObject(ens);
			qo.AddWhere(retrieveKey, retrieveVal);
			qo.addOr();
			qo.AddWhere(key1, val1);
			qo.addOrderBy(orderBy);
			qo.DoQuery();
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			QueryObject qo = new QueryObject(ens);
			qo.AddWhere(retrieveKey, retrieveVal);
			qo.addOr();
			qo.AddWhere(key1, val1);
			qo.addOrderBy(orderBy);
			qo.DoQuery();
			return ens.ToJson("dt");
		}


		if (this.getPK().equals("WorkID") == true)
		{
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			QueryObject qo = new QueryObject(ens);
			qo.AddWhere(retrieveKey, retrieveVal);
			qo.addOr();
			qo.AddWhere(key1, val1);
			qo.addOrderBy(orderBy);
			qo.DoQuery();
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			QueryObject qo = new QueryObject(ens);
			qo.AddWhere(retrieveKey, retrieveVal);
			qo.addOr();
			qo.AddWhere(key1, val1);
			qo.addOrderBy(orderBy);
			qo.DoQuery();
			return ens.ToJson("dt");
		}
		throw new RuntimeException("err@没有判断的 entity 类型. Entities_Retrieve ");
	}

	public final String Entities_Delete() throws Exception {
		Entities ens = ClassFactory.GetEns(this.getClassID());
        if (ens != null) {
            ens.RetrieveAll();
        } else {
			return "err@未找到实体 [" + this.getClassID() + "]";
		}
        bp.wf.httphandler.WF_Comm hand = new WF_Comm();
		return hand.Entities_Delete_Ext(ens);
	}
	public final String Entities_RetrieveIn() throws Exception {
		String RetrieveKey = this.GetRequestVal("Key");
		String RetrieveValues = this.GetRequestVal("Vals");
		if (this.getPK().equals("No"))
		{
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			ens.RetrieveIn(RetrieveKey, RetrieveValues);
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("MyPK"))
		{
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			ens.RetrieveIn(RetrieveKey, RetrieveValues);
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("NodeID"))
		{
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			ens.RetrieveIn(RetrieveKey, RetrieveValues);
			return ens.ToJson("dt");
		}


		if (this.getPK().equals("WorkID"))
		{
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			ens.RetrieveIn(RetrieveKey, RetrieveValues);
			return ens.ToJson("dt");
		}

		if (this.getPK().equals("OID"))
		{
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			ens.RetrieveIn(RetrieveKey, RetrieveValues);
			return ens.ToJson("dt");
		}
		throw new RuntimeException("err@没有判断的 entity 类型. Entities_Retrieve ");
	}
	public final String Entities_RetrieveLikeKey() throws Exception {
		String searchKey = this.GetRequestVal("SearchKey");
		String attrsScop = this.GetRequestVal("AttrsScop");
		String condAttr = this.GetRequestVal("CondAttr");
		String condVal = this.GetRequestVal("CondVal");
		String orderBy = this.GetRequestVal("OrderBy");

		if (this.getPK().equals("No") == true)
		{
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			QueryObject qo = new QueryObject(ens);

			String[] strs = attrsScop.split("[,]", -1);

			qo.addLeftBracket();
			for (String str : strs)
			{
				if (DataType.IsNullOrEmpty(str) == true)
				{
					continue;
				}
				qo.AddWhere(str, " LIKE ", "'%" + searchKey + "%'");
				qo.addOr();
			}
			qo.AddWhere(" 1=2 ");
			qo.addRightBracket();

			if (DataType.IsNullOrEmpty(condAttr) == false)
			{
				qo.addAnd();
				qo.AddWhere(condAttr, "=", condVal);
			}
			if (DataType.IsNullOrEmpty(orderBy) == false)
			{
				qo.addOrderBy(orderBy);
			}
			qo.DoQuery();
			return ens.ToJson("dt");
		}
		if (this.getPK().equals("MyPK") == true)
		{
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			QueryObject qo = new QueryObject(ens);

			String[] strs = attrsScop.split("[,]", -1);

			qo.addLeftBracket();
			for (String str : strs)
			{
				if (DataType.IsNullOrEmpty(str) == true || str.equals("MyPK"))
				{
					continue;
				}
				qo.AddWhere(str, " LIKE ", "'%" + searchKey + "%'");
				qo.addOr();
			}
			qo.AddWhere(" 1=2 ");
			qo.addRightBracket();

			if (DataType.IsNullOrEmpty(condAttr) == false)
			{
				qo.addAnd();
				qo.AddWhere(condAttr, "=", condVal);
			}
			if (DataType.IsNullOrEmpty(orderBy) == false)
			{
				qo.addOrderBy(orderBy);
			}
			qo.DoQuery();
			return ens.ToJson("dt");
		}
		if (this.getPK().equals("OID") == true)
		{
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			QueryObject qo = new QueryObject(ens);

			String[] strs = attrsScop.split("[,]", -1);

			qo.addLeftBracket();
			for (String str : strs)
			{
				if (DataType.IsNullOrEmpty(str) == true)
				{
					continue;
				}
				qo.AddWhere(str, " LIKE ", "'%" + searchKey + "%'");
				qo.addOr();
			}
			qo.AddWhere(" 1=2 ");
			qo.addRightBracket();

			if (DataType.IsNullOrEmpty(condAttr) == false)
			{
				qo.addAnd();
				qo.AddWhere(condAttr, "=", condVal);
			}
			if (DataType.IsNullOrEmpty(orderBy) == false)
			{
				qo.addOrderBy(orderBy);
			}
			qo.DoQuery();
			return ens.ToJson("dt");
		}
		return "err@没有判断的类型Entities_RetrieveLikeKey:" + this.getPK();
	}

	/**
	 * 分页模糊查询 - 返回完整分页信息
	 * 前端参数:
	 * - Keyword: 搜索关键词
	 * - SearchAttrs: 搜索字段，逗号分隔的字符串
	 * - PageIndex: 页码(从1开始)
	 * - PageSize: 每页记录数
	 * - OrderBy: 排序字段
	 * @return JSON格式的分页结果
	 * @throws Exception
	 */
	public final String RetrieveLikeByPageWithInfo() throws Exception {
		String keyword = this.GetRequestVal("Keyword");
		String searchAttrsStr = this.GetRequestVal("SearchAttrs");
		String pageIndexStr = this.GetRequestVal("PageIndex");
		String pageSizeStr = this.GetRequestVal("PageSize");
		String orderBy = this.GetRequestVal("OrderBy");

		// 参数验证
		if (DataType.IsNullOrEmpty(pageIndexStr)) {
			return "err@缺少参数PageIndex";
		}
		if (DataType.IsNullOrEmpty(pageSizeStr)) {
			return "err@缺少参数PageSize";
		}

		int pageIndex;
		int pageSize;
		try {
			pageIndex = Integer.parseInt(pageIndexStr);
			pageSize = Integer.parseInt(pageSizeStr);
		} catch (NumberFormatException e) {
			return "err@页码或页面大小参数格式错误";
		}

		if (pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize < 1) {
			pageSize = 10;
		}

		// 处理搜索字段 - 将逗号分隔的字符串转换为数组
		String[] searchAttrs = null;
		if (!DataType.IsNullOrEmpty(searchAttrsStr)) {
			searchAttrs = searchAttrsStr.split(",");
			// 去除空白字符
			for (int i = 0; i < searchAttrs.length; i++) {
				searchAttrs[i] = searchAttrs[i].trim();
			}
		}

		// 根据不同的主键类型处理
		PageResult pageResult = null;
		
		if (this.getPK().equals("No")) {
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			pageResult = ens.RetrieveLikeByPageWithInfo(keyword, searchAttrs, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("MyPK")) {
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			pageResult = ens.RetrieveLikeByPageWithInfo(keyword, searchAttrs, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("OID")) {
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			pageResult = ens.RetrieveLikeByPageWithInfo(keyword, searchAttrs, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("NodeID")) {
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			pageResult = ens.RetrieveLikeByPageWithInfo(keyword, searchAttrs, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("WorkID")) {
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			pageResult = ens.RetrieveLikeByPageWithInfo(keyword, searchAttrs, pageIndex, pageSize, orderBy);
		}
		else {
			return "err@没有判断的主键类型 RetrieveLikeByPageWithInfo:" + this.getPK();
		}

		if (pageResult == null) {
			return "err@查询失败";
		}

		// 构建返回的JSON结果
		JSONObject result = new JSONObject();
		result.put("PageIndex", pageResult.getPageIndex());
		result.put("PageSize", pageResult.getPageSize());
		result.put("TotalCount", pageResult.getTotalCount());
		result.put("TotalPages", pageResult.getTotalPages());
		result.put("CurrentPageCount", pageResult.getCurrentPageCount());
		result.put("HasPrevious", pageResult.isHasPrevious());
		result.put("HasNext", pageResult.isHasNext());
		result.put("IsFirstPage", pageResult.isFirstPage());
		result.put("IsLastPage", pageResult.isLastPage());
		result.put("StartIndex", pageResult.getStartIndex());
		result.put("EndIndex", pageResult.getEndIndex());
		result.put("IsEmpty", pageResult.isEmpty());
		
		// 添加数据 - 修复：直接解析JSON字符串为对象
		Entities data = pageResult.getData();
		String dataJsonStr = data.ToJson("dt");
		try {
			JSONObject dataJson = JSONObject.parseObject(dataJsonStr);
			result.put("Data", dataJson);
		} catch (Exception e) {
			// 如果解析失败，作为字符串返回（向后兼容）
			result.put("Data", dataJsonStr);
		}

		return result.toJSONString();
	}

	/**
	 * 基本分页查询 - 返回完整分页信息
	 * 前端参数:
	 * - WhereAttr: 条件字段(可选)
	 * - WhereVal: 条件值(可选)
	 * - PageIndex: 页码(从1开始)
	 * - PageSize: 每页记录数
	 * - OrderBy: 排序字段
	 * @return JSON格式的分页结果
	 * @throws Exception
	 */
	public final String RetrieveByPageWithInfo() throws Exception {
		String whereAttr = this.GetRequestVal("WhereAttr");
		String whereVal = this.GetRequestVal("WhereVal");
		String pageIndexStr = this.GetRequestVal("PageIndex");
		String pageSizeStr = this.GetRequestVal("PageSize");
		String orderBy = this.GetRequestVal("OrderBy");

		// 参数验证
		if (DataType.IsNullOrEmpty(pageIndexStr)) {
			return "err@缺少参数PageIndex";
		}
		if (DataType.IsNullOrEmpty(pageSizeStr)) {
			return "err@缺少参数PageSize";
		}

		int pageIndex;
		int pageSize;
		try {
			pageIndex = Integer.parseInt(pageIndexStr);
			pageSize = Integer.parseInt(pageSizeStr);
		} catch (NumberFormatException e) {
			return "err@页码或页面大小参数格式错误";
		}

		if (pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize < 1) {
			pageSize = 10;
		}

		// 根据不同的主键类型处理
		PageResult pageResult = null;
		
		if (this.getPK().equals("No")) {
			TSEntitiesNoName ens = new TSEntitiesNoName(this.getClassID());
			pageResult = ens.RetrieveByPageWithInfo(whereAttr, whereVal, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("MyPK")) {
			TSEntitiesMyPK ens = new TSEntitiesMyPK(this.getClassID());
			pageResult = ens.RetrieveByPageWithInfo(whereAttr, whereVal, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("OID")) {
			TSEntitiesOID ens = new TSEntitiesOID(this.getClassID());
			pageResult = ens.RetrieveByPageWithInfo(whereAttr, whereVal, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("NodeID")) {
			TSEntitiesNodeID ens = new TSEntitiesNodeID(this.getClassID());
			pageResult = ens.RetrieveByPageWithInfo(whereAttr, whereVal, pageIndex, pageSize, orderBy);
		}
		else if (this.getPK().equals("WorkID")) {
			TSEntitiesWorkID ens = new TSEntitiesWorkID(this.getClassID());
			pageResult = ens.RetrieveByPageWithInfo(whereAttr, whereVal, pageIndex, pageSize, orderBy);
		}
		else {
			return "err@没有判断的主键类型 RetrieveByPageWithInfo:" + this.getPK();
		}

		if (pageResult == null) {
			return "err@查询失败";
		}

		// 构建返回的JSON结果
		JSONObject result = new JSONObject();
		result.put("PageIndex", pageResult.getPageIndex());
		result.put("PageSize", pageResult.getPageSize());
		result.put("TotalCount", pageResult.getTotalCount());
		result.put("TotalPages", pageResult.getTotalPages());
		result.put("CurrentPageCount", pageResult.getCurrentPageCount());
		result.put("HasPrevious", pageResult.isHasPrevious());
		result.put("HasNext", pageResult.isHasNext());
		result.put("IsFirstPage", pageResult.isFirstPage());
		result.put("IsLastPage", pageResult.isLastPage());
		result.put("StartIndex", pageResult.getStartIndex());
		result.put("EndIndex", pageResult.getEndIndex());
		result.put("IsEmpty", pageResult.isEmpty());
		
		// 添加数据 - 修复：直接解析JSON字符串为对象
		Entities data = pageResult.getData();
		String dataJsonStr = data.ToJson("dt");
		try {
			JSONObject dataJson = JSONObject.parseObject(dataJsonStr);
			result.put("Data", dataJson);
		} catch (Exception e) {
			// 如果解析失败，作为字符串返回（向后兼容）
			result.put("Data", dataJsonStr);
		}

		return result.toJSONString();
	}

	/**
	 * 批量更新
	 * @return
	 * @throws Exception
	 */
	public final String Entities_Update() throws Exception {
		JSONObject json = JSONObject.parseObject(this.GetRequestVal("Row"));
		if(json == null) {
			return "err@请传入要更新的数据Ï";
		}
		String idListStr = this.GetRequestVal("IdListStr");
		Entities ens = ClassFactory.GetEns(this.getClassID());
		if(ens == null) {
			return "err@获取实体失败，请检查参数，className = " + this.getEnsName();
		}
		Entity en = ens.getNewEntity();
		if(en == null) {
			return "err@获取实体失败，请检查参数，className = " + this.getEnsName();
		}
		String PKField = ens.getNewEntity().getPK();
		String pTable = en.getEnMap().getPhysicsTable();
		StringBuilder sql = new StringBuilder("update " + pTable + " set ");
		for(String key: json.keySet()) {
            Object val = json.get(key);
            // 判断数据类型，如果是 String，则加上单引号
            if (val instanceof String) {
                sql.append(key).append("='").append(val).append("',");
            } else {
                sql.append(key).append("=").append(val).append(",");
            }
		}
		sql.deleteCharAt(sql.length() - 1);
		return updateByRange(idListStr, PKField, sql);
	}

	/**
	 * 从某一列更新
	 * @return
	 * @throws Exception
	 */
	public final String Entities_UpdateFromColumn() throws Exception {
		Entities ens = ClassFactory.GetEns(this.getClassID());
		if(ens == null) {
			return "err@获取实体失败，请检查参数，className = " + this.getEnsName();
		}
		Entity en = ens.getNewEntity();
		if(en == null) {
			return "err@获取实体失败，请检查参数，className = " + this.getEnsName();
		}
		String fromColumn = this.GetRequestVal("FromColumn");
		String toColumn = this.GetRequestVal("ToColumn");
		String idListStr = this.GetRequestVal("IdListStr");
		String PKField = ens.getNewEntity().getPK();
		String pTable = en.getEnMap().getPhysicsTable();
		StringBuilder sql = new StringBuilder("update " + pTable + " set ");
		sql.append(fromColumn).append("=").append(toColumn);
		return updateByRange(idListStr, PKField, sql);
	}

	private String updateByRange(String idListStr, String PKField, StringBuilder sql) {
		if(idListStr != null) {
			String[] ids = Arrays.stream(idListStr.split(",")).map(String::trim).map(id -> "'" + id + "'").toArray(String[]::new);
			if(ids.length > 0) {
				sql.append(" where ").append(PKField).append(" in (").append(StringUtils.join(ids, ",")).append(")");
			}
		}
		DBAccess.RunSQL(sql.toString());
		return "更新成功";
	}


	/**
	 * 通过id删除集合数据
	 * @return
	 * @throws Exception
	 */
	public final String Entities_DeleteByIdList() throws Exception {
		Entities ens = ClassFactory.GetEns(this.getClassID());
		if(ens == null) {
			return "err@获取实体失败，请检查参数，className = " + this.getEnsName();
		}
		Entity en = ens.getNewEntity();
		if(en == null) {
			return "err@获取实体失败，请检查参数，className = " + this.getEnsName();
		}
		String PKField = ens.getNewEntity().getPK();
		String pTable = en.getEnMap().getPhysicsTable();
		String idListArgs = this.GetRequestVal("idList");
		if(StringUtils.isBlank(idListArgs)) {
			return "err@请传入要删除的id";
		}
		String reverse = this.GetRequestVal("reverse");
		String r = "";
		if(StringUtils.isNotBlank(reverse) && reverse.equals("1")) {
			r = "not";
		}
		String idList = Arrays.stream(idListArgs.split(",")).map(String::trim).map(id -> "'" + id + "'").collect(Collectors.joining(","));
		String sql = "DELETE FROM " + pTable + " WHERE " + PKField + " " + r + " in (" + idList + ")";
		DBAccess.RunSQL(sql);
		return "删除成功";
	}

	/**
	 执行删除
	 @return
	*/
	public final String Entity_Delete() throws Exception {
		bp.sys.base.Glo.WriteEntityLog("实体数据删除");
		DBRoles dbRoles = new DBRoles();
		dbRoles.Retrieve(DBRoleAttr.FrmID, this.getClassID(), DBRoleAttr.DBRole, "RecDelete", DBRoleAttr.IsEnable, 1);
		if (dbRoles.size()>0 && CheckDBRole(dbRoles) == false)
			return "err@您没有删除的权限";
		if (this.getPK().equals("No"))
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID());
			en.setNo(this.getPKVal());
			en.RetrieveFromDBSources();

			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (!DataType.IsNullOrEmpty(this.getRefEnName()))
			{
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				int i = enServ.Delete();

				en.Delete(); //执行本实体的删除.
				return String.valueOf(i);
			}

			return String.valueOf(en.Delete());
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID());
			en.setMyPK(this.getPKVal());
			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (DataType.IsNullOrEmpty(this.getRefEnName()) == false)
			{
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				int i = enServ.Delete();

				en.Delete(); //执行本实体的删除.
				return String.valueOf(i);
			}

			return String.valueOf(en.Delete());
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID());
			en.setOID(this.getPKValInt());
			en.RetrieveFromDBSources();

			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (DataType.IsNullOrEmpty(this.getRefEnName()) == false)
			{
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				int i = enServ.Delete();

				en.Delete(); //执行本实体的删除.
				return String.valueOf(i);
			}

			return String.valueOf(en.Delete());
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID());
			en.setWorkID(this.getPKValInt());

			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (DataType.IsNullOrEmpty(this.getRefEnName()) == false)
			{
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				int i = enServ.Delete();

				en.Delete(); //执行本实体的删除.
				return String.valueOf(i);
			}


			return String.valueOf(en.Delete());
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID());
			en.setNodeID(this.getPKValInt());

			//判断是否有对应的后端实体类，如果有则要执行更新.
			if (DataType.IsNullOrEmpty(this.getRefEnName()) == false)
			{
				Entity enServ = ClassFactory.GetEn(this.getRefEnName());
				if (enServ == null)
				{
					throw new RuntimeException("err@TS实体类[" + this.getClassID() + "]关联的[" + this.getRefEnName() + "]拼写错误,");
				}

				enServ.setPKVal(this.getPKVal());
				enServ.RetrieveFromDBSources();
				int i = enServ.Delete();

				en.Delete(); //执行本实体的删除.
				return String.valueOf(i);
			}

			return String.valueOf(en.Delete());
		}

		throw new RuntimeException("err@没有判断的entity类型. Entity_Delete ");
	}

	public final String Entity_Upload() throws Exception {
		HttpServletRequest request = ContextHolderUtils.getRequest();
		float size =CommonFileUtils.getFilesSize(request,"file");
		if (size== 0)
		{
			return "err@请选择要上传的文件。";
		}
		//获取保存文件信息的实体
		String saveTo = this.GetRequestVal("SaveTo");
		String realSaveTo = "";
		if (DataType.IsNullOrEmpty(saveTo) == true)
		{
			realSaveTo = SystemConfig.getPathOfDataUser() + "UploadFile/";
			saveTo = "/DataUser/UploadFile/";
		}
		else
		{
			if (saveTo.startsWith("/DataUser"))
			{
				if(SystemConfig.isJarRun())
					realSaveTo = SystemConfig.getPhysicalPath()+ saveTo;
				else
					realSaveTo = SystemConfig.getPathOfWebApp() + saveTo;
			}
		}
		//获取文件的名称
		String fileName = CommonFileUtils.getOriginalFilename(request,"file");
		if(fileName.indexOf("\\")>-1){
			fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
		}
		if(fileName.indexOf("/")>-1){
			fileName = fileName.substring(fileName.lastIndexOf("/")+1);
		}
		fileName = fileName.replace(" ","");
		String fileRealName = fileName.substring(0, fileName.lastIndexOf('.'));
		//文件后缀
		String ext = FileAccess.getExtensionName(fileName).toLowerCase().replace(".", "");

		//文件大小
		size = size  / 1024;

		File info = new File(saveTo);
		CommonFileUtils.upload(request,"file", new File(realSaveTo + fileName));

		///#region 上传RTF模板时，清空缓存
		if (saveTo.indexOf("/DataUser/CyclostyleFile/") != -1)
		{
			bp.da.Cache.getBill_Cache().clear();
			if (SystemConfig.getRedisIsEnable()) {
				bp.da.Cache.getBill_Cache_Redis().clear();
			}
		}
        ///#endregion 上传RTF模板时，清空缓存

		AtPara para = new AtPara();
		para.SetVal("FileName", fileRealName);
		para.SetVal("FileExt", ext);
		para.SetVal("FileSize", String.valueOf(size));
		para.SetVal("FilePath", saveTo + fileName + ext);
		String saveInfo = para.GenerAtParaStrs();
		if (this.getPK().equals("No") == true)
		{
			TSEntityNoName en = new TSEntityNoName(this.getClassID(), this.getPKVal());
			en.setNo(this.getPKVal());
			en.SetValByKey(this.getKeyOfEn(), saveInfo);
			return String.valueOf(en.DirectUpdate());
		}

		if (this.getPK().equals("MyPK") == true)
		{
			TSEntityMyPK en = new TSEntityMyPK(this.getClassID(), this.getPKVal());
			en.setMyPK(this.getPKVal());
			en.SetValByKey(this.getKeyOfEn(), saveInfo);
			return String.valueOf(en.DirectUpdate());
		}

		if (this.getPK().equals("OID") == true)
		{
			TSEntityOID en = new TSEntityOID(this.getClassID(), this.getPKValInt());
			en.setOID(this.getPKValInt());
			en.SetValByKey(this.getKeyOfEn(), saveInfo);
			return String.valueOf(en.DirectUpdate());
		}

		if (this.getPK().equals("NodeID") == true)
		{
			TSEntityNodeID en = new TSEntityNodeID(this.getClassID(), this.getPKValInt());
			en.setNodeID(this.getPKValInt());
			en.SetValByKey(this.getKeyOfEn(), saveInfo);
			return String.valueOf(en.DirectUpdate());
		}

		if (this.getPK().equals("WorkID") == true)
		{
			TSEntityWorkID en = new TSEntityWorkID(this.getClassID(), this.getPKValInt());
			en.setWorkID(this.getPKValInt());
			en.SetValByKey(this.getKeyOfEn(), saveInfo);
			return String.valueOf(en.DirectUpdate());
		}
		return "上传成功";
	}

	public final String Entity_DBRoleAttrs() throws Exception {
		if(DataType.IsNullOrEmpty(this.getEnName())==true)
			return "";
		DBRoles dbRoles = new DBRoles();
		dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"ShowAttrs",DBRoleAttr.IsEnable,1);
		return CheckDB(dbRoles);
	}
	public final String Entity_DBRoleMethods() throws Exception {
		if(DataType.IsNullOrEmpty(this.getEnName())==true)
			return "";
		DBRoles dbRoles = new DBRoles();
		dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"ShowMethod",DBRoleAttr.IsEnable,1);
		return CheckDB(dbRoles);
	}
	private String CheckDB(DBRoles dbRoles) throws Exception {
		if (dbRoles.size() == 0)
			return "";
		Entity en  = dbRoles.GetEntityByKey(DBRoleAttr.MarkID,"None") ;
		if(en!=null)
			return "";
		//获取是否存在管理员，二级管理员
		en  = dbRoles.GetEntityByKey(DBRoleAttr.MarkID,"Adminer") ;
		if(en !=null && WebUser.getNo().equals("admin"))
			return "";
		String keyOfEns = ",";
		for (DBRole dbRole : dbRoles.ToJavaList())
		{
			String strs = ","+dbRole.getDocs()+",";
			String sql = "";
			//二级管理员
			if (dbRole.getMarkID().equals("Admin2") == true)
			{
				if (WebUser.getIsAdmin() == true)
				{
					keyOfEns += dbRole.GetValStringByKey("Objs") + ",";
					break;
				}
			}
			//如果是部门.
			if (dbRole.getMarkID().equals("ByDepts") == true)
			{
				sql = "SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" + WebUser.getNo() + "'";
				sql += " UNION ";
				sql += "SELECT FK_Dept FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.getNo() + "'";

				DataTable mydt = DBAccess.RunSQLReturnTable(sql);
				for (DataRow mydr : mydt.Rows)
				{
					String myNo = mydr.getValue(0).toString();
					if (strs.contains("," + myNo + ",") == true)
					{
						keyOfEns+=dbRole.GetValStringByKey("Objs")+",";
						break;
					}
				}
			}

			//如果标记是岗位.
			if (dbRole.getMarkID().equals("ByStations") == true)
			{
				sql = "SELECT FK_Station FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.getNo() + "'";
				DataTable mydt = DBAccess.RunSQLReturnTable(sql);
				for (DataRow mydr : mydt.Rows)
				{
					String myNo = mydr.getValue(0).toString();
					if (strs.contains("," + myNo + ",") == true)
					{
						keyOfEns+=dbRole.GetValStringByKey("Objs")+",";
						break;
					}
				}
			}

			//指定的人是否可以查看全部数据?.
			if (dbRole.getMarkID().equals("ByEmps") == true)
			{
				if (strs.contains("," + WebUser.getNo() + ",") == true)
				{
					keyOfEns+=dbRole.GetValStringByKey("Objs")+",";
					break;
				}
			}

		}
		return keyOfEns;
	}
	public final String Entity_UAC() throws Exception {
		Entity en = ClassFactory.GetEn(this.getEnName());
		if(en == null)
			throw new RuntimeException("err@没有获取到实体["+this.getEnName()+"]的实体信息");
		String pkval = this.getPKVal();
		if (DataType.IsNullOrEmpty(pkval)==false)
		{
			en.setPKVal(pkval);
			en.RetrieveFromDBSources();
		}
		Hashtable ht = new Hashtable();
		DBRoles dbRoles = new DBRoles();
		dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"RecNew",DBRoleAttr.IsEnable,1);
		if(dbRoles.size()>0)
			ht.put("IsInsert",CheckDBRole(dbRoles)?1:0);
		else
			ht.put("IsInsert",2);
		if(en.getEnMap().getAttrs().GetAttrByKey("EditType")!=null &&  en.GetValIntByKey("EditType")!=0){
			ht.put("IsDelete",0);
		}else{
			dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"RecDelete",DBRoleAttr.IsEnable,1);
			if(dbRoles.size()>0)
				ht.put("IsDelete",CheckDBRole(dbRoles)?1:0);
			else
				ht.put("IsDelete",2);
		}

		dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"RecSave",DBRoleAttr.IsEnable,1);
		if(dbRoles.size()>0)
			ht.put("IsUpdate",CheckDBRole(dbRoles)?1:0);
		else
			ht.put("IsUpdate",2);

		dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"ImpExcel",DBRoleAttr.IsEnable,1);
		if(dbRoles.size()>0)
			ht.put("IsImp",CheckDBRole(dbRoles)?1:0);
		else
			ht.put("IsImp",2);

		dbRoles.Retrieve(DBRoleAttr.FrmID,this.getEnName(),DBRoleAttr.DBRole,"ExpExcel",DBRoleAttr.IsEnable,1);
		if(dbRoles.size()>0)
			ht.put("IsExp",CheckDBRole(dbRoles)?1:0);
		else
			ht.put("IsExp",2);

		return bp.tools.Json.ToJson(ht);


	}
	private boolean CheckDBRole(DBRoles dbRoles) throws Exception {
		Entity en  = dbRoles.GetEntityByKey(DBRoleAttr.MarkID,"None") ;
		if(en!=null)
			return true;
		//获取是否存在管理员，二级管理员
		en  = dbRoles.GetEntityByKey(DBRoleAttr.MarkID,"Adminer") ;
		if(en !=null && WebUser.getNo().equals("admin"))
			return true;
		if(WebUser.getNo().equals("admin"))
			return true;
		for (DBRole dbRole : dbRoles.ToJavaList())
		{
			String strs = ","+dbRole.getDocs()+",";
			String sql = "";
			//二级管理员
			if (dbRole.getMarkID().equals("Admin2") == true)
			{
				if (WebUser.getIsAdmin() == true)
					return true;
			}
			if (dbRole.getMarkID().equals("SelfOnly") == true || dbRole.getMarkID().equals("DeptLeader") == true )
			{
				//查询列表页不能确保删除功能
				if(DataType.IsNullOrEmpty(this.GetRequestVal("PKVal")))
					return true;
				String enName = this.getEnName();
				if(enName == null) enName = this.getClassID();
				Entity entity = ClassFactory.GetEn(enName);
				entity.SetValByKey(entity.getPK(),this.GetRequestVal("PKVal"));
				entity.RetrieveFromDBSources();
				if(dbRole.getMarkID().equals("SelfOnly")){
					String starter = entity.GetValStringByKey("RecNo","");
					if(DataType.IsNullOrEmpty(starter))
						starter = entity.GetValStringByKey("Starter","");
					if(DataType.IsNullOrEmpty(starter))
						starter = entity.GetValStringByKey("FlowStarter","");
					if(DataType.IsNullOrEmpty(starter)==false && starter.equals(WebUser.getNo()))
						return true;
					continue;
                }
				if (dbRole.getMarkID().equals("DeptLeader") == true)
				{
					String deptNo = entity.GetValStringByKey("DeptNo","");
					String deptLeader = DBAccess.RunSQLReturnString("SELECT Leader FROM Port_Dept WHERE No='" + deptNo + "'");
					if (deptLeader != null && deptLeader.equals(WebUser.getNo()) == true)
					{
						return true;
					}
				}

			}

			//如果是部门.
			if (dbRole.getMarkID().equals("ByDepts") == true)
			{
				sql = "SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" + WebUser.getNo() + "'";
				sql += " UNION ";
				sql += "SELECT FK_Dept FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.getNo() + "'";

				DataTable mydt = DBAccess.RunSQLReturnTable(sql);
				for (DataRow mydr : mydt.Rows)
				{
					String myNo = mydr.getValue(0).toString();
					if (strs.contains("," + myNo + ",") == true)
						return true;
				}
			}

			//如果标记是岗位.
			if (dbRole.getMarkID().equals("ByStations") == true)
			{
				sql = "SELECT FK_Station FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.getNo() + "'";
				DataTable mydt = DBAccess.RunSQLReturnTable(sql);
				for (DataRow mydr : mydt.Rows)
				{
					String myNo = mydr.getValue(0).toString();
					if (strs.contains("," + myNo + ",") == true)
						return true;
				}
			}

			//指定的人是否可以查看全部数据?.
			if (dbRole.getMarkID().equals("ByEmps") == true)
			{
				if (strs.contains("," + WebUser.getNo() + ",") == true)
					return true;
			}

			//按照SQL
			if (dbRole.getMarkID().equals("ByExp") == true)
			{
				String exp = dbRole.getDocs();
				exp = exp.replace("~","'");
				exp = exp.replace("@Key",this.GetRequestVal("PKVal"));
				exp = bp.wf.Glo.DealExp(exp, null);
				if(DBAccess.RunSQLReturnValInt(exp) > 0)
					return true;
			}
		}
		return false;
	}

	/**
	 * 从表3D大小类
	 * @return
	 * @throws Exception
	 */
	public final String Sort1Sort2D3_Init() throws Exception {
		Entity en =  ClassFactory.GetEn(this.getEnName());
		if(en == null)
			return "err@参数类名不正确.";
		DataSet ds = new DataSet();
		Attrs attrs = en.getEnMap().getAttrs();
		//获取Sort1
		Attr attr = attrs.GetAttrByKey(this.GetRequestVal("Sort1"));
		if(attr.getItIsEnum())
			return "err@一维字段不能是枚举类型";
		DataTable dt = null;
		//Sort1处理
		String uiBindKey = attr.getUIBindKey();
		if(uiBindKey.toUpperCase().contains("SELECT") == true){
			uiBindKey = bp.wf.Glo.DealExp(uiBindKey,null);
			dt = DBAccess.RunSQLReturnTable(uiBindKey);
			dt.TableName = "Sort1";
			ds.Tables.add(dt);
		}else{
			if(uiBindKey.startsWith("Ens,")){
				String[] strs = uiBindKey.split(",");
				uiBindKey = strs[strs.length-1];
			}
			dt = bp.pub.PubClass.GetDataTableByUIBineKey(uiBindKey, null);
			dt.TableName = "Sort1";
			ds.Tables.add(dt);
		}
		//Sort2处理
		attr = attrs.GetAttrByKey(this.GetRequestVal("Sort2"));
		uiBindKey = attr.getUIBindKey();
		if(uiBindKey.toUpperCase().contains("SELECT") == true){
			uiBindKey = bp.wf.Glo.DealExp(uiBindKey,null);
			dt = DBAccess.RunSQLReturnTable(uiBindKey);
			dt.TableName = "Sort2";
			ds.Tables.add(dt);
		}else{
			if(uiBindKey.startsWith("Ens,")){
				String[] strs = uiBindKey.split(",");
				uiBindKey = strs[strs.length-1];
			}
			dt = bp.pub.PubClass.GetDataTableByUIBineKey(uiBindKey, null);
			dt.TableName = "Sort2";
			ds.Tables.add(dt);
		}

		//Sort3处理

		attr = attrs.GetAttrByKey(this.GetRequestVal("Sort3"));
		uiBindKey = attr.getUIBindKey();
		if(attr.getItIsEnum()){
			SysEnums sysEnums = new SysEnums(uiBindKey);
			dt = new DataTable("Sort3");
			dt.Columns.Add("No");
			dt.Columns.Add("Name");
			DataRow dr = null;
			for(SysEnum sysEnum:sysEnums.ToJavaList()){
				dr = dt.NewRow();
				dr.setValue("No",sysEnum.getIntKey());
				dr.setValue("Name",sysEnum.getLab());
				dt.Rows.add(dr);
			}
			ds.Tables.add(dt);

		}else{
			if(uiBindKey.toUpperCase().contains("SELECT") == true){
				uiBindKey = bp.wf.Glo.DealExp(uiBindKey,null);
				dt = DBAccess.RunSQLReturnTable(uiBindKey);
				dt.TableName = "Sort3";
				ds.Tables.add(dt);
			}else{
				if(uiBindKey.startsWith("Ens,")){
					String[] strs = uiBindKey.split(",");
					uiBindKey = strs[strs.length-1];
				}
				dt = bp.pub.PubClass.GetDataTableByUIBineKey(uiBindKey, null);
				dt.TableName = "Sort3";
				ds.Tables.add(dt);
			}
		}


		return bp.tools.Json.ToJson(ds);
	}
	public final String Dtl2DFixRow_Init() throws Exception {
		Entity en =  ClassFactory.GetEn(this.getEnName());
		if(en == null)
			return "err@参数类名不正确.";
		DataSet ds = new DataSet();
		Attrs attrs = en.getEnMap().getAttrs();
		//获取Sort1
		Attr attr = attrs.GetAttrByKey(this.GetRequestVal("Sort1"));
		if(attr.getItIsEnum())
			return "err@一维字段不能是枚举类型";
		DataTable dt = null;
		//Sort1处理
		String uiBindKey = attr.getUIBindKey();
		if(uiBindKey.toUpperCase().contains("SELECT") == true){
			uiBindKey = bp.wf.Glo.DealExp(uiBindKey,null);
			dt = DBAccess.RunSQLReturnTable(uiBindKey);
			dt.TableName = "Sort1";
			ds.Tables.add(dt);
		}else{
			if(uiBindKey.startsWith("Ens,")){
				String[] strs = uiBindKey.split(",");
				uiBindKey = strs[strs.length-1];
			}
			dt = bp.pub.PubClass.GetDataTableByUIBineKey(uiBindKey, null);
			dt.TableName = "Sort1";
			ds.Tables.add(dt);
		}
		//Sort2处理
		attr = attrs.GetAttrByKey(this.GetRequestVal("Sort2"));
		uiBindKey = attr.getUIBindKey();
		if(uiBindKey.toUpperCase().contains("SELECT") == true){
			uiBindKey = bp.wf.Glo.DealExp(uiBindKey,null);
			dt = DBAccess.RunSQLReturnTable(uiBindKey);
			dt.TableName = "Sort2";
			ds.Tables.add(dt);
		}else{
			if(uiBindKey.startsWith("Ens,")){
				String[] strs = uiBindKey.split(",");
				uiBindKey = strs[strs.length-1];
			}
			dt = bp.pub.PubClass.GetDataTableByUIBineKey(uiBindKey, null);
			dt.TableName = "Sort2";
			ds.Tables.add(dt);
		}
		return bp.tools.Json.ToJson(ds);
	}

}
